import time
from datetime import datetime, timedelta

from flask import render_template, request, jsonify, session, g, redirect, url_for

from info import constants, db
from info.common import user_login_data
from info.models import User, News, Category
from info.modules.admin import admin_blu
from info.utils.image_storage import storage
from info.utils.response_code import RET


@admin_blu.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        # 如果未点退出进入登录界面直接跳转到主页
        user_id = session.get("user_id", None)
        is_admin = session.get("is_admin", False)
        if user_id and  is_admin:
            return redirect(url_for('admin.index'))
        return render_template("admin/login.html")
    # 获取参数，校验，跳转到主页，保持状态
    username = request.form.get("username")
    password = request.form.get("password")
    if not all(["username", "password"]):
        return jsonify(errno=RET.DATAERR, errmsg="参数不足")
    try:
        user = User.query.filter(User.nick_name == username).first()
    except Exception as f:
        print(f)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")
    if not user:
        return jsonify(errno=RET.USERERR, errmsg="用户不存在")
    if not user.check_passowrd(password):
        return jsonify(errno=RET.PWDERR, errmsg="密码错误")
    if not user.is_admin:
        return render_template('admin/login.html', errmsg="用户权限错误")
    # 保持状态
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["is_admin"] = True
    session["mobile"] = user.mobile
    return redirect(url_for('admin.index'))


@admin_blu.route("/index")
@user_login_data
def index():
    user = g.user
    data = {
        "user":user
    }
    return render_template("admin/index.html", data=data)


@admin_blu.route("/user_count")
@user_login_data
def user_count():
    # 查询总人数
    total_count = 0
    mon_count = 0
    day_count = 0
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as f:
        print(f)
    # 返回时间对象(显示当前的时间)
    t = time.localtime()
    # 没有传入时分秒默认为0:0:0
    # mon_begin_date =  datetime.strptime('2018-6-29', '%Y-%m-%d')
    mon_begin_date = datetime.strptime(('%d-%02d-1') % (t.tm_year, t.tm_mon), '%Y-%m-%d')

    try:
        mon_count = User.query.filter(User.is_admin == False, User.create_time > mon_begin_date).count()
    except Exception as f:
        print(f)
    # 创建时间>今天时间0:0:0即可
    day_begin_date = datetime.strptime(("%d-%02d-%02d" % (t.tm_year, t.tm_mon, t.tm_mday)), '%Y-%m-%d')
    try:
        day_count = User.query.filter(User.is_admin == False, User.create_time > day_begin_date).count()
    except Exception as f:
        print(f)

    active_count = []
    active_date = []
    for i in range(0,31):
        begin_date = day_begin_date - timedelta(days=i)
        end_adte = day_begin_date - timedelta(days=(i-1))
        count = 0
        try:
            # 查询每天活跃的人数(时间-->人数)
            # 查询每一天的人数(判断用户最后登录的时间:今天的23:59:59(明天的0:0:0即可)<time<今天的0:0:0)
            count = User.query.filter(User.is_admin == False, begin_date<= User.last_login, User.last_login < end_adte).count()
        except Exception as f:
            print(f)
        active_count.append(count)
        active_date.append(begin_date.strftime('%Y-%m-%d'))
    active_count.reverse()
    active_date.reverse()
    data = {
        "total_count": total_count,
        "mon_count": mon_count,
        "day_count": day_count,
        "active_count": active_count,
        "active_date": active_date
    }
    return render_template("admin/user_count.html", data=data)


@admin_blu.route("/user_list")
@user_login_data
def user_list():
    page = request.args.get("p", 1)
    current_page = 1
    pages = 1
    paginate_list = []
    try:
        page = int(page)
    except Exception as f:
        print(f)
        return jsonify(errno=RET.NODATA, errmsg="无参数")
    try:
        paginate = User.query.filter(User.is_admin == False).order_by(User.last_login.desc()).paginate(page, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
        paginate_list = paginate.items
        current_page =paginate.page
        pages = paginate.pages
    except Exception as f:
        print(f)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")
    paginates = []
    for paginate in paginate_list:
        paginates.append(paginate.to_admin_dict())
    conrtent = {
        "current_page":current_page,
        "pages":pages,
        "paginates":paginates,
    }
    return render_template("admin/user_list.html", data=conrtent)


@admin_blu.route("/news_review")
@user_login_data
def news_review():
    page = request.args.get("p", 1)
    current_page = 1
    pages = 1
    keywords = request.args.get("keywords")
    try:
        page = int(page)
    except Exception as f:
        print(f)
        return jsonify(errno=RET.NODATA, errmsg="无参数")
    news_list = []
    filters=[News.status != 0]
    if keywords:
        filters.append(News.title.contains(keywords))
    try:
        news_list = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
        paginate_list = news_list.items
        current_page = news_list.page
        pages = news_list.pages
    except Exception as f:
        print(f)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")
    paginates = []
    for paginate in paginate_list:
        paginates.append(paginate.to_review_dict())
    content = {
        "current_page": current_page,
        "pages": pages,
        "paginates": paginates
    }
    return render_template("admin/news_review.html", data=content)


@admin_blu.route('/news_review_detail', methods=["GET", "POST"])
def news_review_detail():
    """新闻审核"""
    if request.method == "GET":
        # 根据新闻id返回相应的数据
        news_id = request.args.get("news_id")
        news_object = None
        try:
            news_id = int(news_id)
        except Exception as f:
            print(f)
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        try:
            news_object = News.query.get(news_id)
        except Exception as f:
            print(f)
            return jsonify(errno=RET.DBERR, errsg="数据查询失败")
        if not news_object:
            return jsonify(errno=RET.DBERR, errmsg="未查询到数据")
        data = {
            "news":news_object.to_dict()
        }
        return render_template("admin/news_review_detail.html",data=data)
    news_id = request.json.get("news_id")
    action = request.json.get("action")
    if not all(["news_id", "action"]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    try:
        news_id = int(news_id)
    except Exception as f:
        print(f)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if action not in ("accept", "reject"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    news = None
    try:
        # 3.查询新闻
        news = News.query.get(news_id)
    except Exception as f:
        print(f)
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到数据")
    if action == "accept":
        # 设置状态
        news.status = 0
    else:
        # 拒绝通过，需要获取原因
        reason = request.json.get("reason")
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        news.reason = reason
        news.status = -1
    # 保存数据库
    try:
        db.session.commit()
    except Exception as f:
        print(f)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")
    return jsonify(errno=RET.OK, errmsg="操作成功")


@admin_blu.route("/news_edit")
def news_edit():
    """
    新闻版式编辑

    :return:
    """
    page = request.args.get("p", 1)
    keywords = request.args.get("keywords", "")
    current_page = 1
    total_page = 1
    try:
        page = int(page)
    except Exception as f:
        print(f)
    filters = []
    if keywords:
        try:
            filters.append(News.title.contains(keywords))
        except Exception as f:
            print(f)
    try:
        paginates =  News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        current_page = paginates.page
        total_page = paginates.pages
        paginate_list = paginates.items
    except Exception as f:
        print(f)
    paginate_dict_list = []
    for paginate in paginate_list:
        paginate_dict_list.append(paginate.to_basic_dict())
    data = {
        "current_page":current_page,
        "total_page":total_page,
        "news_list":paginate_dict_list
    }
    return render_template("admin/news_edit.html", data=data)


@admin_blu.route("/news_edit_detail", methods=["GET", "POST"])
def news_edit_detail():
    """新闻板式编辑详情"""
    if request.method == "GET":
        news_id = request.args.get("news_id")
        try:
            news_id = int(news_id)
        except Exception as f:
            print(f)
        try:
            news = News.query.get(news_id)
        except Exception as f:
            print(f)
        if not news_id:
            return render_template('admin/news_edit_detail.html', data={"errmsg": "未查询到此新闻"})
        if not news:
            return render_template('admin/news_edit_detail.html', data={"errmsg": "未查询到此新闻"})
        try:
            categorys = Category.query.all()
        except Exception as f:
            print(f)
        if not categorys:
            return render_template('admin/news_edit_detail.html', data={"errmsg": "未查询到此新闻"})
        category_list = []
        for category in categorys:
            c_category = category.to_dict()
            c_category["is_selected"] = False
            if category.id == news.category_id:
                c_category["is_selected"] = True
            category_list.append(c_category)
        category_list.pop(0)
        data = {
            "news":news.to_dict(),
            "categories":category_list
        }
        return  render_template("admin/news_edit_detail.html", data=data)
    """
    修改编辑
    """
    # 根据新闻id查询到这条新闻，将修改的内容保存到数据库中
    news_id = request.form.get("news_id")
    category_id = request.form.get("category_id")
    title = request.form.get("title")
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image", None)
    if not all(["category_id", "title", "digest", "content"]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    try:
        category_id = int(category_id)
    except Exception as f:
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    try:
        news = News.query.get(news_id)
    except Exception as f:
        return jsonify(errno=RET.NODATA, errmsg="未查询到新闻数据")
    if index_image:
        # 上传到七牛云上
        try:
            index_image = index_image.read()
        except Exception as f:
            print(f)
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
        try:
            key = storage(index_image)
        except Exception as f:
            print(f)
            return jsonify(errno=RET.THIRDERR, errmsg="上传失败")
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.content = content
    try:
        db.session.commit()
    except Exception as f:
        print(f)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据库失败")
    return jsonify(errno=RET.OK, errmsg="OK")


@admin_blu.route("/news_category", methods=["GET", "POST"])
def get_news_category():
    if request.method == "GET":
        try:
            categorys = Category.query.all()
        except Exception as f:
            print(f)
            return render_template('admin/news_type.html', data={"errmsg": "数据库查询失败"})
        if not categorys:
            return render_template('admin/news_type.html', data={"errmsg": "参数错误"})
        category_list = []
        for category in categorys:
            category_list.append(category.to_dict())
        category_list.pop(0)
        data = {
            "categories": category_list
        }
        return render_template('admin/news_type.html', data=data)
    category_id = request.json.get("id")
    # 修改的值(可能是id中要修改的，也可能是增加的)
    category_name = request.json.get("name")
    if not category_name:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if category_id:
        try:
            category_id = int(category_id)
        except Exception as f:
            print(f)
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        try:
            category = Category.query.get(category_id)
        except Exception as f:
            print(f)
            return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")
        category.name = category_name
        try:
            db.session.commit()
        except Exception as f:
            print(f)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")
    else:
        # 初始化模型添加字段
        category = Category()
        category.name = category_name
        try:
            db.session.add(category)
            db.session.commit()
        except Exception as f:
            print(f)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")
    return jsonify(errno=RET.OK, errmsg="OK")
